/**
 * copyright (C), 2018-2019
 * fileName: DbFactory
 * author:   hatrick
 * date:     2019-08-09 16:26
 * description: 封装mybaties的SQL执行
 */
package com.cheng.mybatisutils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 封装mybatis的SQL执行
 *
 * @author hatrick
 * @create 2019-08-09 16:26
 * @since 1.0.0
 */
public class DBFactory {
    public static final String SIGN = "sign";

    private static Logger logger = LoggerFactory.getLogger(DBFactory.class);
    private static ConcurrentHashMap<String, SqlSessionFactory> concurrentHashMap = new ConcurrentHashMap<String, SqlSessionFactory>();
    private SqlSession session;

    public DBFactory(String environmentId) {
        session = createSession(environmentId, false);
    }

    public DBFactory(String environmentId, boolean autoCommit) {
        session = createSession(environmentId, autoCommit);
    }

    public <TMapper> TMapper getMapper(Class<TMapper> mapperClass) {
        return session.getMapper(mapperClass);
    }

    public boolean transaction(ITransaction iTransaction) {
        if (iTransaction.onTransaction()) {
            session.commit();
            return true;
        }
        session.rollback();
        return false;
    }


    public void close() {
        session.close();
    }

    /**
     * 获取sqlSession
     */
    private SqlSession createSession(String environmentId, boolean autoCommit) {
        try {
            if (!concurrentHashMap.containsKey(environmentId)) {
                concurrentHashMap.put(environmentId, new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("application.yml"), environmentId));
            }
            return concurrentHashMap.get(environmentId).openSession(autoCommit);
        } catch (IOException e) {
            logger.error("fail to get sqlSession :", e);
            return null;
        }
    }
}
